/* eslint-disable jsx-a11y/no-autofocus */
import { useState, useCallback } from 'react';
import { View, Text, Input } from '@tarojs/components';
import classnames from 'classnames';
import './style.<%= css %>';

interface IUiinput {
  label?: string;
  value?: string | undefined;
  inputStyle?: any;
  password?: boolean;
  focus?: boolean;
  onInput?: (e: any) => void;
  [propName: string]: any;
}

export default function (props: IUiinput) {
  const { label, value = '', inputStyle = {}, password, focus, onInput } = props;
  const [inputFocus, setInputFocus] = useState(false);
  const [passControlType, setPassControlType] = useState(password);
  const [inputValue, setInputValue] = useState(value);
  const recordInput = (e) => {
    setInputValue(e.detail.value);
    typeof onInput === 'function' && onInput(e);
    setTimeout(() => setInputValue(e.detail.value));
  };
  const inputLength = String(inputValue || '').length;

  // 显示/隐藏密码，小程序切换input type后必须聚焦一次才能变化
  const showPassword = useCallback(() => {
    setPassControlType(!passControlType);
    setInputFocus(false);
    setTimeout(() => setInputFocus(true), 0);
  }, [passControlType]);

  return (
    <View className="ui-input">
      {label ? <Text className="input-label">{label}</Text> : null}
      <Input
        {...props}
        className="input-com"
        focus={password ? inputFocus : focus}
        password={passControlType}
        value={inputValue}
        style={inputStyle}
        onInput={recordInput}
      />

      <View className="expand-area">
        {password && inputLength ? (
          <View
            onClick={showPassword}
            className={classnames(['show-pass-icon', { 'eyes-open': passControlType, 'eyes-close': !passControlType }])}
          />
        ) : null}
      </View>
    </View>
  );
}
